package org.budo.support.spring.web.multipart.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.budo.support.lang.util.FileUtil;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class MultipartFileUtil {
    public static InputStream getInputStream(MultipartFile multipartFile) {
        try {
            return multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getContentByDispositionName(String requestBody, String dispositionName) {
        if (null == requestBody || null == dispositionName) {
            log.error("#64 getContentByDispositionName error, requestBody=" + requestBody + ", dispositionName=" + dispositionName);
            return null;
        }

        int a = requestBody.indexOf("Content-Disposition: form-data;");

        String boundary = requestBody.substring(0, a).trim();

        int from = 0;
        while (true) {
            int index = requestBody.indexOf(boundary, from);
            if (index < 0) {
                break; // 没有了
            }

            // 一个项
            String item = requestBody.substring(from, index);
            String disposition = "Content-Disposition: form-data; name=\"" + dispositionName + "\"";
            int b = item.indexOf(disposition);
            if (b < 0) { // 不是要找的项
                from = index + boundary.length();
                continue; // 继续找
            }

            // 找到了
            int c = item.indexOf("\r\n\r\n");
            String val = item.substring(c).trim();
            if (val.endsWith("EOF")) {
                val = val.substring(0, val.length() - 3).trim();
            }

            return val;
        }

        return null;
    }

    public static void transferTo(MultipartFile multipartFile, File file) {
        FileUtil.createNewFile(file);

        try {
            multipartFile.transferTo(file);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}